<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="../../vue.js"></script>
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <input type="text" placeholder="请输入年龄" v-model.number="age" />
      <ul>
        <li v-for="item in newPerson">
          <p>姓名：{{item.name}},年龄：{{item.age}}</p>
        </li>
      </ul>
      <button @click="order=1">升序</button>
      <button @click="order=2">降序</button>
    </div>
    <script>
      const vm = new Vue({
        el: '#app',
        data() {
          return {
            age: 0, //和表单中输入的内容关联
            person: [
              { id: '001', name: 'lucy', age: 22 },
              { id: '002', name: 'lili', age: 12 },
              { id: '003', name: 'yuehan', age: 31 },
              { id: '004', name: 'liming', age: 18 },
              { id: '005', name: 'xiaowang', age: 4 },
              { id: '006', name: 'zhangsan', age: 19 },
              { id: '007', name: 'wangwu', age: 40 },
            ],
            order: 0, //创建变量用来储存排序，1为升序，2为降序
          };
        },
        computed: {
          newPerson() {
            // 先过滤
            const filterPerson = this.person.filter((item) => {
              return this.age < item.age; //item及为person中的每个对象，this.age是表单中输入的年龄，将person中每个年龄大于表单中输入的数据返回出来，返回的结果是一个新数组,而列表应该循环这个新数组
            });
            // 再排序
            if (this.order === 1) {
              return filterPerson.sort((a, b) => {
                // a,b是过滤后的person中的对象,要比较的是对象中的age
                return a.age - b.age;
              });
            } else {
              return filterPerson.sort((a, b) => {
                // a,b是过滤后的person中的对象
                return b.age - a.age;
              });
            }
          },
        },
      });
    </script>
  </body>
</html>
